package cn.tedu.csmall.product.service.impl;


import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.*;
import cn.tedu.csmall.product.pojo.param.BrandAddNewParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.BrandListItemVo;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVo;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.product.service.BrandService;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j  /*要养成写日志的习惯*/
@Service
public class brandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Override
    public void addNew(BrandAddNewParam brandAddNewParam) {
        log.debug("开始处理【添加品牌】的业务,参数: {}",brandAddNewParam);
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",brandAddNewParam.getName());
        int countByName = brandMapper.selectCount(queryWrapper);
        log.debug("根据品牌名称统计匹配的品牌数量，结果：{}", countByName);
        if (countByName>0){
            String message = "添加品牌失败，品牌名称已经被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        // 将相册数据写入到数据库中
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewParam, brand);
        brand.setSales(0);
        brand.setProductCount(0);
        brand.setCommentCount(0);
        brand.setPositiveCommentCount(0);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());

        log.debug("准备将新的品牌数据写入到数据库，数据：{}", brand);
        int rows = brandMapper.insert(brand);
        if (rows != 1){
            String message = "添加品牌失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("将新的品牌数据写入到数据库，完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除品牌】的业务,参数: {}",id);
        //检查品牌是否存在，如果不存在，则抛出异常
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById = brandMapper.selectCount(queryWrapper);
        log.debug("根据品牌ID统计匹配的品牌数量，结果：{}", countById);
        if (countById == 0){
            String message = "删除品牌失败，品牌数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //检查是否有品牌类别关联到此品牌，如果存在，则抛出异常
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("brand_id",id);
        int countByBrandId2 = brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据品牌ID统计匹配的品牌类别数量，结果：{}", countByBrandId2);
        if (countByBrandId2 > 0){
            String message = "删除品牌失败，仍有品牌类别关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //检查是否有spu关联到此品牌，如果存在，则抛出异常
        QueryWrapper<Spu> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("brand_id",id);
        int countByBrandId3 = spuMapper.selectCount(queryWrapper3);
        log.debug("根据品牌ID统计匹配的spu数量，结果：{}", countByBrandId3);
        if (countByBrandId3 > 0){
            String message = "删除品牌失败，仍有spu关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        int rows = brandMapper.deleteById(id);
        if (rows != 1){
            String message = "删除品牌失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        log.debug("删除品牌成功!");
    }

    @Override
    public void updateBrand(Long brandId, BrandUpdateInfoParam brandUpdateInfoParam) {
        Brand brand = brandMapper.selectById(brandId);
        if (brand == null){
            String message = "修改品牌失败,根据品牌id没有找到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //检查品牌名称是否被其他品牌占用，如果被占用，则抛出异常
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",brandUpdateInfoParam.getName())
                .ne("id",brandId);
        int countById = brandMapper.selectCount(queryWrapper);
        if (countById > 0){
            String message = "修改品牌失败，该名称已存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        BeanUtils.copyProperties(brandUpdateInfoParam,brand);
        brand.setGmtModified(LocalDateTime.now());
        int rows = brandMapper.updateById(brand);
        if (rows != 1){
            String message = "修改品牌失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }

    @Override
    public PageData<BrandListItemVo> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<BrandListItemVo> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询品牌列表】的业务，页码:{},每页条数:{}",pageNum,pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<BrandListItemVo> list = brandMapper.list();
        PageInfo<BrandListItemVo> pageInfo = new PageInfo<>(list);
        PageData<BrandListItemVo> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，pageData：{}",pageData);
        return pageData;
    }

    @Override
    public BrandStandardVo getStandardById(Long id) {
        log.debug("开始处理【根据ID查询品牌详情】的业务，参数:{}",id);
        BrandStandardVo brandStandardVo = brandMapper.getStandardById(id);
        if (brandStandardVo == null){
            String message = "查询品牌失败，没有此数据";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return brandStandardVo;
    }

}
